<?php

namespace App\Http\Controllers\WF\Systems;

use DB;
use Carbon\Carbon;
use App\Http\Controllers\WF\ApiController;
use Illuminate\Http\Request;
use App\Eloqumd\Wf\WfDictType;
use App\Eloqumd\Wf\WfDict;
use App\Eloqumd\Wf\WfDictAccess;
use App\Http\Requests\WF\DictRequest;
use App\Http\Requests\WF\DictTypeRequest;

class DictsController extends ApiController
{
    /**
     * 获取字典类型列表
     *
     * @name    getDictTypeList
     *
     * @return 	array                       返回结果
     */
    public function getDictTypeList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $request->input('keyword', '');
        $where = null;
        $orWhere = [];
        // 快捷搜索-名称,代码
        if ($keyword) {
            $orWhere[] = ['name', 'like', "%{$keyword}%", 'AND'];
            $orWhere[] = ['code', 'like', "%{$keyword}%", 'OR'];
        }

        $whereIn = [];
        if ($this->apiUser['user_type'] != 0) {
            $dictAuths = WfDictAccess::where('company_id', $this->apiUser['company_id'])->value('dicts');
            if (!$dictAuths) {
                return $this->jsonReturns(10000, $this->success, [
                    'list' => [],
                    'count' => 0
                ]);
            }
            $whereIn = ['id', explode(',', $dictAuths)];
        }

        $totalCount = WfDictType::where($where)
            ->where(function ($query) use ($orWhere) {
                if ($orWhere) $query->orWhere($orWhere);
            })->where(function ($query) use ($whereIn) {
                if ($whereIn) $query->whereIn($whereIn[0], $whereIn[1]);
            })->count();
        $listData = WfDictType::where($where)
            ->where(function ($query) use ($orWhere) {
                if ($orWhere) $query->orWhere($orWhere);
            })->where(function ($query) use ($whereIn) {
                if ($whereIn) $query->whereIn($whereIn[0], $whereIn[1]);
            })
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = [
            'list' => $listData,
            'count' => $totalCount
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData);
    }

    /**
     * 通过ID获取字典类型详情
     *
     * @name    getDictTypeById
     *
     * @return 	array                       返回结果
     */
    public function getDictTypeById(Request $request)
    {
        $id = $request->input('id', 0);
        $data = WfDictType::find($id)->toArray();

        return $this->jsonReturns(10000, $this->success, $data);
    }

    /**
     * 添加字典类型
     *
     * @name    dictTypeCrd
     *
     * @return 	array                       返回结果
     */
    public function dictTypeCrd(DictTypeRequest $request)
    {
        $request->validate('crd');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = new WfDictType;
            $model->name = $param['name'];
            $model->code = strtoupper($param['code']);
            $model->remark = $param['remark'] ?? '';
            $model->created_id = $this->apiUser['id'];
            $model->created_by = $this->apiUser['realname'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 编辑字典类型
     *
     * @name    dictTypeEdt
     *
     * @return 	array                       返回结果
     */
    public function dictTypeEdt(DictTypeRequest $request)
    {
        $request->validate('edt');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = WfDictType::find($param['id']);
            $model->name = $param['name'];
            $model->remark = $param['remark'] ?? '';
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 删除字典类型
     *
     * @name    dictTypeEdt
     *
     * @return 	array                       返回结果
     */
    public function dictTypeRmv(DictTypeRequest $request)
    {
        $request->validate('rmv');
        $id = $request->input('id', 0);

        DB::beginTransaction();
        try {
            //校验是否存在子菜单
            if (WfDict::where('parent_id', $id)->count()) {
                return $this->jsonReturns(60000, trans('wf.WF-The-Dict-Type-Has-Detail-Dicts'));
            }

            $model = WfDictType::find($id);
            $model->delete();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 字典详情列表
     *
     * @name    getDictList
     *
     * @return 	array                       返回结果
     */
    public function getDictList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        $parent_id = $request->input('parent_id', '');
        $where = null;
        $where[] = ['parent_id', '=', $parent_id, 'AND'];
        $where[] = ['company_id', '=', $this->apiUser['company_id'], 'AND'];

        $totalCount = WfDict::where($where)->count();
        $listData = WfDict::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = [
            'list' => $listData,
            'count' => $totalCount
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData);
    }

    /**
     * 字典详情获取
     *
     * @name    getDictById
     *
     * @return 	array                       返回结果
     */
    public function getDictById(Request $request)
    {
        $id = $request->input('id', 0);
        $data = WfDict::find($id)->toArray();

        return $this->jsonReturns(10000, $this->success, $data);
    }

    /**
     * 字典详情添加
     *
     * @name    dictCrd
     *
     * @return 	array                       返回结果
     */
    public function dictCrd(DictRequest $request)
    {
        $request->validate('crd');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = new WfDict;
            $model->name = $param['name'];
            $model->parent_id = $param['parent_id'];
            $model->status = $param['status'];
            $model->orders = $param['orders'];
            $model->company_id = $this->apiUser['company_id'];
            $model->created_id = $this->apiUser['id'];
            $model->created_by = $this->apiUser['realname'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 字典详情编辑
     *
     * @name    dictCrd
     *
     * @return 	array                       返回结果
     */
    public function dictEdt(DictRequest $request)
    {
        $request->validate('edt');
        $param = $request->all();

        DB::beginTransaction();
        try {
            $model = WfDict::find($param['id']);
            $model->name = $param['name'];
            $model->status = $param['status'];
            $model->orders = $param['orders'];
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 字典详情删除
     *
     * @name    dictRmv
     *
     * @return 	array                       返回结果
     */
    public function dictRmv(Request $request)
    {
        $id = $request->input('id');
        DB::beginTransaction();
        try {
            WfDict::whereIn('id', explode(',', rtrim($id, ',')))->delete();

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }

    /**
     * 字典详情启用禁用
     *
     * @name    dictRmv
     *
     * @return 	array                       返回结果
     */
    public function dictSts(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status', 0);

        DB::beginTransaction();
        try {
            WfDict::whereIn('id', explode(',', rtrim($id, ',')))->update([
                'status' => $status,
                'updated_at' => Carbon::now()
            ]);

            DB::commit();

            return $this->jsonReturns(10000, $this->success);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage());
        }
    }
}
